import {types} from 'mobx-state-tree';
import {MenuStore, Menu, IMenu} from './MenuStore';
import {Templates} from './PageTemplates';

export const PageManageStore = types
    .model('PageManageStore', {
        menuStore: types.late(() => types.optional(MenuStore, {})),
        isAddPageShow: false,
        menuIdSelected: 'root',
    })
    .views(self => ({}))
    .actions(self => {

        const selectMenu = (menuId: string): void => {
            self.menuStore.clearMenuActive()
            self.menuIdSelected = menuId
        }

        const addPageShow = (isShow: boolean) => {
            self.isAddPageShow = isShow
        }

        const addSubMenu = (data: {
            label: string;
            path: string;
            template: number;
            icon?: string;
        }) => {
            const newId = crypto.randomUUID();
            let subMenu = Menu.create({
                ...data,
                path: '/pageManage/' + newId,
                schema: Templates[data.template],
                id: newId
            });

            let menuSelected = self.menuStore.getMenuById(self.menuIdSelected);
            if (menuSelected) {
                menuSelected.addSubMenu(subMenu)
                self.menuStore.saveMenus()
            }

            self.isAddPageShow = false
        }

        return {
            selectMenu,
            addPageShow,
            addSubMenu,
            afterCreate() {
                self.menuStore.load();
                if (self.menuStore.menus[0]) {
                    self.menuStore.menus[0].active = true
                }
                self.isAddPageShow = false
            }
        };
    });

export type IPageManageStore = typeof PageManageStore;
